import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";

import { useUserStore } from "@/store/user";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeView.vue"),
    meta: { requiresAuth: false },
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginView.vue"),
    meta: { requiresAuth: false },
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/",
  },
  {
    path: "/workFlow",
    name: "workFlow",
    component: () => import("../views/workFlow.vue"),
    meta: { requiresAuth: false },
  },
  {
    path: "/workDetail",
    name: "workflowDetail",
    component: () => import("../views/workflowDetail.vue"),
    meta: { requiresAuth: false },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, _, next) => {
  const userStore = useUserStore();
  const isAuthenticated = !!userStore.userInfo?.phone;

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 未登录，重定向到登录页，并记录目标路径
    next({ name: "login", query: { redirect: to.fullPath } });
  } else if (to.name === "login" && isAuthenticated) {
    // 已登录访问登录页，重定向到首页
    next({ name: "home" });
  } else {
    next();
  }
});

export default router;
